﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Accouting804.Utils;
using Xamarin.Forms.Xaml;


using Accouting804.Models.Orm;
using System.IO;
using System.Reflection;

using SQLitePCL;

using SQLite;
using System.Drawing;
using Accouting804.Services;
using System.Linq.Expressions;

namespace Accouting804.Setting
{



    public class InitializeSetting
    {

        public static SQLiteConnection AccountConnection()
        {
            var connection = new SQLiteConnection(AccountRecordsDbPath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.SharedCache);
            return connection;
        }
        public static SQLiteAsyncConnection AccountAsyncConnection()
        {
            var connection = new SQLiteAsyncConnection(AccountRecordsDbPath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.SharedCache);
            return connection;
        }

        public static string SettingDBPath
        {
            get
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "setting.sqlite");
            }
        }
        public static string AccountRecordsDbPath
        {
            get
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "account.sqlite");
            }
        }

        public static bool AccountDBExistAndComplete()
        {
            try
            {
                using (var connection = new SQLiteConnection(AccountRecordsDbPath, SQLiteOpenFlags.ReadWrite))
                {
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        public static bool SettingDBExist()
        {
            //try
            //{
            //    using (var connection = new SQLiteConnection(SettingDBPath, SQLiteOpenFlags.ReadWrite))
            //    {
            //    }


            //    return true;
            //}
            //catch (Exception)
            //{
            //    return false;
            //}

            return false;

        }

        public static void InitDb()
        {
            //配置数据库创建
            using (var connection = new SQLite.SQLiteConnection(SettingDBPath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.SharedCache))
            {

                connection.CreateTable<Config>();

            }
            //记账数据库创建
            using (var connection = new SQLiteConnection(AccountRecordsDbPath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.SharedCache))
            {
                var result = connection.CreateTable<AccountRecord>();
                var resultTagTable = connection.CreateTable<Tag>();
                var resultOfCategory = connection.CreateTable<Category>();
                var resultBook = connection.CreateTable<Book>();
                var resultPaymentMethod = connection.CreateTable<PaymentMethod>();
                new List<Category>
                {
                    new Category() { Name="食物"},
                    new Category() { Name="水电租" },
                    new Category() { Name="借还钱" },
                    new Category() { Name="日用杂物" },
                    new Category() { Name="医疗"}
                }.ForEach((a) =>
                {
                    try
                    {
                        connection.Insert(a);
                    }
                    catch (Exception)
                    {
                    }
                });

                new List<Book>
                {
                    new Book(){ Name ="默认账本"}
                }.ForEach((a) =>
                {
                    try
                    {
                        connection.Insert(a);
                    }
                    catch (Exception)
                    {
                    }
                });
                new List<PaymentMethod>
                {
                    new PaymentMethod(){ Name="支付宝"},
                    new PaymentMethod(){ Name="微信"},
                    new PaymentMethod(){ Name="银行卡"},
                    new PaymentMethod(){ Name="现金"}
                }.ForEach((a) =>
                {
                    try
                    {
                        connection.Insert(a);
                    }
                    catch (Exception)
                    {
                    }

                }); ;


            }

            //        }
            //    }
            //    catch (Exception)
            //    {

            //        throw;
            //    }

            //    try
            //    {
            //        using (var connection = new SQLiteConnection(AccountRecordsDbPath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.SharedCache))
            //        {
            //            var mapping = connection.GetMapping<AccountRecord>();
            //            CreateTableResult table = connection.CreateTable<AccountRecord>(CreateFlags.None);



            //        }
            //    }
            //    catch (Exception)
            //    {
            //    }
            //}
        }


        public static void DelelteAllDb()
        {

            new FileInfo(AccountRecordsDbPath).Delete();
            new FileInfo(SettingDBPath).Delete();

        }
    }

    //[System.ComponentModel.DataAnnotations.Schema.Table("Config")]
    [SQLite.Table("Config")]
    public class Config
    {
        [PrimaryKey]
        public string Name { get; set; }
        public string Value { get; set; }
        public string Comment { get; set; }
    }

    //public class ConfigContext : DbContext
    //{
    //    public DbSet<Config> Configs { get; set; }
    //}

    //public class AccountDbContext : DbContext
    //{
    //    public DbSet<AccountRecord> AccountRecords { get; set; }
    //    public DbSet<Tag> Tags { get; set; }

    //    public DbSet<Category> Categories { get; set; }


    //    protected override void OnConfiguring(DbContextOptionsBuilder builder)
    //    {
    //        builder.UseSqlite($"Filename={InitializeSetting.AccountRecordsDbPath}");
    //    }
    //}




    //[System.ComponentModel.DataAnnotations.Schema.Table("AccountRecords")]
    [SQLite.Table("AccountRecords")]
    public class AccountRecord
    {
        [AutoIncrement, PrimaryKey]
        public int AutoId { get; set; }
        public string Name { get; set; }
        public string User { get; set; }
        public decimal Amount { get; set; }
        [Ignore]
        public string DatetimeString
        {
            get
            {
                return $"{DateTime.DateTimeString(OutputDateTimeString.YYYY_MM_DD_sp_hh_mm_ss)}";
            }
        }
        [Ignore]
        public string DateString => $"{DateTime.Year}.{DateTime.Month}.{DateTime.Day}";
        [Ignore]
        public string DisplayString => $"{Name} / {Catagory} / {Book}\n" +
            $"{User} / {Description}";

        public DateTime DateTime { get; set; }
        public string Catagory { get; set; }
        public string Description { get; set; }
        public string Tags { get; set; }
        /// <summary>
        /// 其他
        /// </summary>
        public string Other { get; set; }
        /// <summary>
        /// 支付方式/收钱方式
        /// </summary>
        public string PaymentMethod { get; set; }
        [Ignore]
        public PaymentMethod PaymentMethodObj => DependencyService.Get<IDataStoreWithWhereQuery<PaymentMethod>>().GetItemsWithWhere(x => x.Name == this.PaymentMethod).FirstOrDefault();
        [Ignore]
        public Book BookObj
        {
            get
            {
                var obj = DependencyService.Get<IDataStoreWithWhereQuery<Book>>().GetItemsWithWhere(book => book.Name == this.Book).FirstOrDefault();
                return obj;
            }
        }
        [Ignore]
        public DateTime Date
        {
            get => DateTime.Date;
            set => DateTime = value.Add(DateTime.TimeOfDay);
        }
        [Ignore]
        public TimeSpan TimeOfDay
        {
            get => DateTime.TimeOfDay;
            set => DateTime = DateTime.Date.Add(value);
        }

        /// <summary>
        /// 属于哪个账本
        /// </summary>
        public string Book { get; set; }

    }

    //[System.ComponentModel.DataAnnotations.Schema.Table("Tags")]
    [SQLite.Table("Tags")]
    public class Tag : ITableWithColor
    {
        [AutoIncrement, PrimaryKey]
        //[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public int AutoId { get; set; }
        //[Unique, NotNull]
        [Unique, NotNull]
        public int Name { get; set; }

        /// <summary>
        /// 颜色hex,例"#1122AABB"
        /// </summary>
        public string Color { get; set; }
        [Ignore]
        public Xamarin.Forms.Color ItemColor { get => this.ColorFromProgram(); set => Color = value.ToHex(); }


        public Xamarin.Forms.Color ColorFromProgram() => Xamarin.Forms.Color.FromHex(Color);
    }

    [Table("Categories")]
    public class Category : ITableWithColor
    {
        [AutoIncrement, PrimaryKey]
        public int AutoId { get; set; }
        [NotNull, Unique]
        public string Name { get; set; }

        public string Description { get; set; }

        public int ParentCategoryId { get; set; }



        [Ignore]
        public Category ParentCategory
        {
            get
            {
                var categoryDatastore = DependencyService.Get<CategoryDataStore>();
                throw new NotImplementedException();
            }
        }


        [Ignore]
        public Xamarin.Forms.Color ItemColor { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    }

    /// <summary>
    /// 支付方式/收钱方式
    /// </summary>
    public class PaymentMethod
    {
        [AutoIncrement, PrimaryKey]
        public int AutoId { get; set; }
        [Unique, NotNull]
        public string Name { get; set; }
        public string Description { get; set; }
        public override string ToString()
        {
            return base.ToString();
        }
    }

    /// <summary>
    /// 账本
    /// </summary>
    [Table("Books")]
    public class Book
    {
        [AutoIncrement, PrimaryKey]
        public int AutoId { get; set; }
        [Unique, NotNull]
        public string Name { get; set; }
        public string Description { get; set; }
    }

    public interface ITableWithColor
    {
        Xamarin.Forms.Color ItemColor { get; set; }
    }


}

